mergeInto(LibraryManager.library, {
   DoMicrophoneLibByState: function(state) 
   {		
		switch(state) 
		{
			case 0:
				StartRecord();
				break;	
			case 1:
				StopRecord();
				break;			
			case 2:
				CheckMicrophoneAuthorization();
				break;
			case 3:
				Reset();
				break;
			default:
				console.log('state undefined ' + state);
				break;
		}

		function CheckMicrophoneAuthorization()
		{
			if(!IsMicrophoneAPIAvailable())
			{
				console.log('Microphone Lib is not supported in this browser');
				SendMessage('MicrophoneWebGLModuleNative', 'CheckMicrophoneAuthorizationHandler', 0);	
			}
			else
			{
				navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;			
				SendMessage('MicrophoneWebGLModuleNative', 'CheckMicrophoneAuthorizationHandler', 1);
			}
		}
		
		function IsMicrophoneAPIAvailable()
		{
			return !!(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.mediaDevices.getUserMedia);
		}

		function StartRecord()
		{
			if(!document.audioContext)
			{
				if (navigator.mediaDevices.getUserMedia) {
					navigator.mediaDevices.getUserMedia({
							audio: true
						}).then(GetUserMediaSuccess).catch(GetUserMediaFailed);
				}
			}
			else
			{
				document.script_processor_node.connect(document.audioContext.destination);
				document.microphone_stream.connect(document.script_processor_node);
			}
		}
		
		function MicrophoneProcess(event)
		{
			var microphone_output_buffer = event.inputBuffer.getChannelData(0);

			var stringArray = "";

			for (var i = 0; i < microphone_output_buffer.length; i++) {
				stringArray = stringArray  + microphone_output_buffer[i] + ",";
			}

			SendMessage('MicrophoneWebGLModuleNative', 'WriteBufferFromMicrophoneHandler', stringArray);
		}
		
		function GetUserMediaSuccess(stream)
		{
			document.audioContext = new AudioContext();
			document.microphone_stream = document.audioContext.createMediaStreamSource(stream);
			document.script_processor_node = document.audioContext.createScriptProcessor(16384, 1, 1);	
			document.script_processor_node.onaudioprocess = MicrophoneProcess;

			document.script_processor_node.connect(document.audioContext.destination);
			document.microphone_stream.connect(document.script_processor_node);

			console.log('GetUserMediaSuccess');	
		}
		
		function GetUserMediaFailed(value)
		{
			console.log('Record Failed with message: ' + value);		
		}
		
		function StopRecord()
		{
			if(document.microphone_stream != undefined){
				document.microphone_stream.disconnect(document.script_processor_node);
				document.script_processor_node.disconnect();
			}
		}
		
		function Reset()
		{
			document.audioContext = null;
			document.microphone_stream = null;
			document.script_processor_node = null;
		}
   }
});